const Article = require('../../models/article')
const Tag = require('../../models/tag')

module.exports = (req, res) => {
  const article_id = req.body.id
  // console.log(article_id);
  /*
    1、找出文章
    2、将文章包含的标签找出
    3、将标签从Tag数据库-1
  */
  const tag_id = '62162ed14c4270244c5f60db'
  var fatherArr = []
  Tag.findById({ _id: tag_id }, (err, tagDoc) => {
    // 父数组
    fatherArr = tagDoc.tags
    Article.findById({ _id: article_id }, (err, articleDoc) => {
      // 子数组
      const sonArr = articleDoc.tag
      console.log(sonArr);
      // console.log(articleDoc);

      for (let i = 0; i < sonArr.length; i++) {
        // sonArr[i].tag_name
        // fatherArr[i].tag_name
        const item_i = sonArr[i]
        for (let j = 0; j < fatherArr.length; j++) {
          const item_j = fatherArr[j];
          if (item_i.tag_name === item_j.tag_name) {
            // console.log(j);
            item_j.tag_number = parseInt(item_j.tag_number) - 1
            if (item_j.tag_number <= 0) {
              item_j.tag_number = 0
            }
            item_j.tag_number.toString()
            console.log(item_j.tag_name + ':' + item_j.tag_number);
          }
        }
      }
      // 更新Tag数据库里的文章数量
      Tag.findByIdAndUpdate({_id:tag_id},{tags:fatherArr},(err,newTagDoc) => {
        if (err) {
          return res.status(500).json({
            err_code: 500,
            message: 'Tag的错误:' + err.message
          })
        }
      })

      Article.findByIdAndRemove({
        _id: article_id
      }, (err) => {
        if (err) {
          return res.status(500).json({
            err_code: 500,
            message: err.message
          })
        }
        res.status(200).json({
          err_code: 0,
          message: 'delete success'
        })
      })
    })
  })
}